import React, { Component } from "react";
import {
  DatePicker,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Select,
  Popconfirm,
  Tooltip,
  message
} from "antd";
import UploadImg from "../../component/uploadImg";
import "./ArticleList.less";
import {
  SearchOutlined,
  DeleteOutlined,
  PlusCircleOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  EditOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons";
import "moment/locale/zh-cn";
// 引入编辑器组件
import BraftEditor from "braft-editor";
// 引入编辑器样式
import "braft-editor/dist/index.css";
import locale from "antd/es/date-picker/locale/zh_CN";
import {
  queryArticleList,
  addArticle,
  deleteArticle,
  updateArticle,
  updateArticleStatus,
  batchdeletearticle,
} from "../../api/articleList";

export default class ArticleList extends Component {
  constructor(props) {
    super();
    this.state = {
      editor: BraftEditor.createEditorState(null), //富本文编辑,
      visible: false,
      visibleUp: false,
      editorUp: BraftEditor.createEditorState(null), //富本文编辑,
      visibleDe: false,
      isshow: false,
      selectArr: [],
      article: {
        articleTitle: "",
        articleType: "小说",
        articleAuthor: "",
        articlePic: "",
        articleStatus: 1,
      },
      upArticle: {
        articleTitle: "",
        articleType: "",
        articleAuthor: "",
        articlePic: "",
      },
      columns: [
        {
          key: "Id",
          title: "Id",
          dataIndex: "key",
          align: "center",
          render(text, record, index) {
            return <>{index + 1}</>;
          },
        },
        {
          key: "articleTitle",
          title: "文章标题",
          dataIndex: "articleTitle",
          align: "center",
        },
        {
          key: "articleType",
          title: "文章类型",
          dataIndex: "articleType",
          align: "center",
        },
        {
          key: "articleAuthor",
          title: "作者",
          dataIndex: "articleAuthor",
          align: "center",
        },
        {
          key: "articleContent",
          title: "文章内容",
          dataIndex: "articleContent",
          align: "center",
          render: (item) => <p dangerouslySetInnerHTML={{ __html: item }} />,
        },
        {
          key: "articlePic",
          title: "文章缩略图",
          dataIndex: "articlePic",
          align: "center",
          render(img) {
            return <img style={{ width: "100px" }} src={img} alt="" />;
          },
        },
        {
          key: "articleStatus",
          title: "状态",
          dataIndex: "articleStatus",
          align: "center",
          render: (text, record, index) => (
            <>
              {record.articleStatus === 1 ? (
                <Button type="primary">已启用</Button>
              ) : (
                <Button type="danger">已停用</Button>
              )}
            </>
          ),
        },
        {
          key: "articleHandle",
          title: "操作",
          dataIndex: "articleHandle",
          align: "center",
          render: (text, record, index) => {
            // console.log(record.articleStatus === 1);
            return (
              <>
                {record.articleStatus === 1 ? (
                  <Tooltip title="停用">
                    <Button
                      shape="circle"
                      style={{
                        height: "19px",
                        lineHeight: "16px",
                        color: "#666",
                      }}
                      size="small"
                      icon={
                        <ArrowDownOutlined
                          style={{ fontSize: "12px" }}
                          onClick={() => this.updateStatus(record)}
                        />
                      }
                    />
                  </Tooltip>
                ) : (
                  <Tooltip title="启用">
                    <Button
                      shape="circle"
                      style={{
                        height: "19px",
                        lineHeight: "16px",
                        color: "#666",
                      }}
                      size="small"
                      icon={
                        <ArrowUpOutlined
                          style={{ fontSize: "12px" }}
                          onClick={() => this.updateStatus(record)}
                        />
                      }
                    />
                  </Tooltip>
                )}
                <EditOutlined
                  onClick={() => this.showModalUp(record)}
                  style={{ margin: "0 5px", color: "#666" }}
                />
                <Popconfirm
                  title="亲，你确定要删除吗?"
                  onConfirm={() => this.deleteArticle(record)}
                  okText="确认"
                  cancelText="取消"
                >
                  <DeleteOutlined style={{ color: "#666" }} />
                </Popconfirm>
              </>
            );
          },
        },
      ],
      data: [],
    };
  }
  // 修改状态
  updateStatus(record) {
    console.log("123");
    let status;
    if (record.articleStatus === 1) {
      status = 0;
    } else if (record.articleStatus === 0) {
      status = 1;
    }
    updateArticleStatus({ _id: record._id, articleStatus: status }).then(
      (res) => {
        console.log(res);
        if (res.state === "修改成功") {
          this.getArticleList();
        }
      }
    );
  }
  // 获取数据
  getArticleList() {
    queryArticleList().then((res) => {
      // console.log("getArticleList",res.data);
      let articleArr = res.data;
      articleArr.forEach((item) => {
        item.key = item._id;
      });
      this.setState({
        data: [...articleArr],
      });
    });
  }
  componentDidMount() {
    this.getArticleList();
  }
  // 单删除
  deleteArticle(record) {
    // console.log(record);
    deleteArticle({ _id: record._id }).then((res) => {
      if (res.state === "删除成功") {
        this.getArticleList();
      }
    });
  }
  // 显示添加文章弹窗
  addArticle = () => {
    this.setState({
      defaultChecked: true,
      editor: BraftEditor.createEditorState(null),
      article: {
        ...this.state.article,
        articleTitle: "",
        articleType: "小说",
        articleAuthor: "",
      },
      isshow: false,
      visible: true,
    });
  };
  // 增加文章保存
  handleOk = (e) => {
    // console.log("handleOk",this.state.article);
    this.setState({
      article:{
        ...this.state.article,
        articleContent:this.state.editor.toHTML()
      }
    },
    ()=>{
      addArticle(this.state.article).then((res) => {
        // console.log(res);//{state: "添加成功"}
        if (res.state === "添加成功") {
          this.getArticleList();
          this.setState({
            visible: false,
          });
        }
      });
    })
  };
  // 增加文章取消
  handleCancel = (e) => {
    // console.log(e);
    this.setState({
      visible: false,
    });
  };

  // 显示修改文章弹窗
  showModalUp(record) {
    console.log(record);
    // console.log(record._id)
    // console.log(record.articleType)
    this.setState(
      {
        visibleUp: true,
        editorUp:BraftEditor.createEditorState(record.articleContent),
        upArticle: {
          ...this.state.upArticle,
          _id: record._id,
          articleTitle: record.articleTitle,
          articleType: record.articleType,
          articleAuthor: record.articleAuthor,
          articlePic: record.articlePic,
        },
      },
      () => {
        // console.log(this.state.upArticle.articleType,"articleType")
      }
    );
  }
  // 修改文章保存
  handleOkUp = (e) => {
    this.setState({
      upArticle:{
        ...this.state.upArticle,
        articleContent:this.state.editorUp.toHTML()
      }
    },()=>{
      updateArticle(this.state.upArticle).then((res) => {
        // console.log("this.state.upArticle",this.state.upArticle);
        console.log(res); //{state: "修改成功"}
        if (res.state === "修改成功") {
          this.getArticleList();
          this.setState({
            visibleUp: false,
          });
        }
      });
    })
  };
  // 修改文章取消
  handleCancelUp = (e) => {
    // console.log(e);
    this.setState({
      visibleUp: false,
    });
  };

  // 批量删除文章弹窗
  showModalDe = () => {
    console.log(this.state.selectArr, "批量删除选中项，弹窗显示");
    if(this.state.selectArr.length>=1){
      this.setState({
        visibleDe: true,
      });
    }else{
      message.warning({content:'请先勾选删除项',style: {
        marginTop: "5%",
      }});
      this.setState({
        visibleDe: false,
      });
    }
  };
  // 批量删除保存
  handleOkDe = (e) => {
    console.log(this.state.selectArr, "批量删除选中项，点击保存");
    batchdeletearticle({ strArr: JSON.stringify(this.state.selectArr) }).then(
      (res) => {
        console.log(res);
        if (res.state === "删除成功") {
          this.getArticleList();
          this.setState({
            visibleDe: false,
          });
          message.success('删除成功');
        }
      }
    );
  };
  // 批量删除取消
  handleCancelDe = (e) => {
    // console.log(e);
    this.setState({
      visibleDe: false,
    });
  };

  // 获取图片
  getImgUrl = (imgUrl, isshow) => {
    console.log(imgUrl);
    this.setState({
      isshow: isshow,
      article: {
        ...this.state.article,
        articlePic: imgUrl,
      },
    });
  };
  // 添加双向绑定
  changeVal(e, key) {
    // console.log(key);
    this.setState({
      article: {
        ...this.state.article,
        [key]: e.target.value,
      },
    });
  }
  // 修改双向绑定
  changeUpVal(e, key) {
    // console.log(key);
    this.setState({
      upArticle: {
        ...this.state.upArticle,
        [key]: e.target.value,
      },
    });
  }
  // 文章类型
  handleChange(value) {
    // console.log(value.label); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
    this.setState({
      article: {
        ...this.state.article,
        articleType: value.label,
      },
    });
  }
  // 下拉菜单取值
  handleChangeUp(value) {
    console.log(value.label); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
    this.setState({
      upArticle: {
        ...this.state.upArticle,
        articleType: value.label,
      },
    });
  }
  // 添加富文本
  handleEditorAddChange = (editor) => {
    this.setState({ editor });
  };
  handleEditorUpChange= (editorUp) => {
    this.setState({ editorUp });
  };


  render() {
    return (
      <div className="articleList">
        <div className="searchBox">
          <div className="startDay">
            <span className="dayRange">日期范围</span>
            <DatePicker
              locale={locale}
              allowClear={true}
              placeholder="开始日"
              showToday={false}
              style={{ width: "185px", height: "38px" }}
            />
          </div>
          <DatePicker
            locale={locale}
            allowClear={true}
            placeholder="截止日"
            showToday={false}
            style={{ width: "185px", height: "38px" }}
          />
          <div className="searchTxt">
            <input type="text" placeholder="请输入用户名" />
          </div>
          <Button
            className="searchBtn"
            type="default"
            icon={<SearchOutlined />}
          ></Button>
        </div>
        <div className="btnBox">
          <div className="btnBoxSelect">
            <Button
              className="deleteBtn"
              type="default"
              onClick={this.showModalDe}
              icon={<DeleteOutlined />}
            >
              批量删除
            </Button>
            <Modal
              title="提示信息"
              visible={this.state.visibleDe}
              onOk={this.handleOkDe}
              onCancel={this.handleCancelDe}
              cancelText="取消"
              okText="确定"
              centered
            >
              <Form
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 14 }}
                layout="inline"
              >
                <QuestionCircleOutlined
                  style={{ fontSize: "26px", color: "#F4C706" }}
                />
                <p style={{ lineHeight: "26px", marginLeft: "8px" }}>
                  确定要删除吗？
                </p>
              </Form>
            </Modal>
            <Button
              className="addBtn"
              type="default"
              icon={<PlusCircleOutlined />}
              onClick={this.addArticle}
            >
              添加
            </Button>
          </div>
          <div className="numTotal">
            <span>共有数据：</span>
            <span className="numTotal-num">{this.state.data.length}</span>
            <span>条</span>
          </div>
        </div>
        <div className="tableCon">
          <Table
            rowSelection={{
              type: "checkbox",
              onChange: (selectedRowKeys, selectedRows) => {
                // console.log(
                //   `selectedRowKeys: ${selectedRowKeys}`,
                //   "selectedRows: ",
                //   selectedRows
                // ); //被选中行所有字段
                let arr = selectedRows.map((item) => ({ _id: item._id })); //数组。map(),必须有返回值，返回一个新数组
                // console.log("arr", arr); //被选中行，只有id字段
                this.setState({
                  selectArr: arr,
                });
              },
            }}
            bordered
            columns={this.state.columns}
            dataSource={this.state.data}
          />
          <Modal
            title="添加文章"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            cancelText="取消"
            okText="保存"
            centered
            width={1000}
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 14 }}
              layout="horizontal"
            >
              <Form.Item label="文章标题" required="true">
                <Input
                  value={this.state.article.articleTitle}
                  onChange={(e) => this.changeVal(e, "articleTitle")}
                />
              </Form.Item>
              <Form.Item label="文章类型" required="true">
                <Select
                  labelInValue
                  defaultValue={{ value: "小说" }}
                  onChange={(value) => this.handleChange(value)}
                >
                  <Select.Option value="小说">小说</Select.Option>
                  <Select.Option value="散文">散文</Select.Option>
                  <Select.Option value="诗词">诗词</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="作者" required="true">
                <Input
                  onChange={(e) => this.changeVal(e, "articleAuthor")}
                  value={this.state.article.articleAuthor}
                />
              </Form.Item>
              <Form.Item label="文章缩略图">
                <UploadImg
                  isshow={this.state.isshow}
                  getImgUrl={this.getImgUrl}
                />
              </Form.Item>
              <Form.Item
                label="文章内容"
                className="edit"
                wrapperCol={{ span: 18 }}
              >
                <BraftEditor
                  value={this.state.editor}
                  onChange={this.handleEditorAddChange}
                  style={{ border: "1px solid #d9d9d9" }}
                />
              </Form.Item>
            </Form>
          </Modal>
          <Modal
            title="编辑"
            visible={this.state.visibleUp}
            onOk={this.handleOkUp}
            onCancel={this.handleCancelUp}
            cancelText="取消"
            okText="保存"
            centered
            width={1000}
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 14 }}
              layout="horizontal"
            >
              <Form.Item label="文章标题" required="true">
                <Input
                  onChange={(e) => this.changeUpVal(e, "articleTitle")}
                  value={this.state.upArticle.articleTitle}
                />
              </Form.Item>
              <Form.Item label="文章类型" required="true">
                <Select
                  labelInValue
                  // defaultValue={{ value: this.state.upArticle.articleType }}
                  value={{ value: this.state.upArticle.articleType }}
                  onChange={(value) => this.handleChangeUp(value)}
                >
                  <Select.Option value="小说">小说</Select.Option>
                  <Select.Option value="散文">散文</Select.Option>
                  <Select.Option value="诗词">诗词</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="作者" required="true">
                <Input
                  onChange={(e) => this.changeUpVal(e, "articleAuthor")}
                  value={this.state.upArticle.articleAuthor}
                />
              </Form.Item>
              <Form.Item label="文章缩略图">
                <img src={this.state.upArticle.articlePic} alt="" />
              </Form.Item>
              <Form.Item
                label="文章内容"
                className="edit"
                wrapperCol={{ span: 18 }}
              >
                <BraftEditor
                  value={this.state.editorUp}
                  onChange={this.handleEditorUpChange}
                  style={{ border: "1px solid #d9d9d9" }}
                />
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </div>
    );
  }
}
